package com.macrosolution.exdebito

import java.io.Serializable;
import java.util.List;

/**
 * Pratica
 * A domain class describes the data object and it's mapping to the database
 */
class Pratica implements Serializable { 
	
	def grailsApplication

	/* Default (injected) attributes of GORM */
//	Long	id
//	Long	version
	String identifier
	User user
	AnomaliaBancaria anomaliaBancaria
	Sovraindebitamento sovraindebitamento
	List fileDocument
	
	/* Automatic timestamping of GORM */
	Date	dateCreated
	Date	lastUpdated
	
	static hasMany = [fileDocument : FileDocument]
//	static	belongsTo	= []	// tells GORM to cascade commands: e.g., delete this object if the "parent" is deleted.
//	static	hasOne		= []	// tells GORM to associate another domain object as an owner in a 1-1 mapping
//	static	hasMany		= []	// tells GORM to associate other domain objects for a 1-n or n-m mapping
//	static	mappedBy	= []	// specifies which property should be used in a mapping 
	
	static	constraints = {
		identifier nullable:true
		user nullable:true
		anomaliaBancaria nullable:true
		sovraindebitamento nullable:true
		fileDocument nullable:true
		
    }
	

	static mapping = {
		fileDocument cascade: 'delete, all-delete-orphan'
		anomaliaBancaria cascade: 'delete, all-delete-orphan'
		sovraindebitamento cascade: 'delete, all-delete-orphan'
   }
	
	def beforeInsert(){
		String codPratica
		String userId = this.user.username
		String anomaliaTip = this.anomaliaBancaria.anomaliaBancariaType.siglaAnomaliaBancaria
		AnomaliaCounter ac = AnomaliaCounter.findByInterIDAndAnomalID(this.anomaliaBancaria.interviewId,this.anomaliaBancaria.anomaliaBancariaType.id)
		String anomaliaNum = ac.counter
		def c = grailsApplication.mainContext.getBean('com.macrosolution.exdebito.utility.UtilityTagLib')
		anomaliaNum = c.double_number('value':anomaliaNum)
		String idInterview = this.anomaliaBancaria.interviewId
		idInterview = c.number_interview('value':idInterview)
		codPratica = (userId + anomaliaTip + anomaliaNum + idInterview).toUpperCase()
		this.identifier = codPratica
	}
	
	/*
	 * Methods of the Domain Class
	 */
//	@Override	// Override toString for a nicer / more descriptive UI 
//	public String toString() {
//		return "${name}";
//	}
	public boolean isEditableByUser(User fromUser){
		User owner = this.user
		boolean result =false;
		if(fromUser.id.equals(owner.id)){
			result=true;
		}else if(fromUser.subjects){
			result=editableByUsers(owner,fromUser.subjects);
		}
		return result
	}
	
	private boolean editableByUsers(User owner,List<User> subjects){
		boolean result=false;
			for(User sub:subjects){
				if(owner.id.equals(sub.id)){
					result=true;
				}else if(sub.subjects){
						result=editableByUsers(owner.owner,sub.subjects);
				}
			}
		return result;
	}
}
